package com.example.demo1.interceptors;

import com.example.demo1.utils.ThreadLocalUtil;
import com.example.demo1.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

//登录拦截器

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String s = request.getHeader("Authorization");
        //验证token
        try {
            //从redis中获取相同的token
            ValueOperations<String, String> operations= stringRedisTemplate.opsForValue();
            String redisToken = operations.get(s);
            if (redisToken == null) {
                //token
                throw new RuntimeException();
            }
            Map<String, Object> map = JwtUtil.parseToken(s);
           ThreadLocalUtil.set(map);
            return true;
        } catch (Exception e) {
            //验证失败，不放行
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       //清空ThreadLocal中的数据，防止溢出
        ThreadLocalUtil.remove();
    }
}